package com.example.demo.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.example.demo.mapper.SysConfigMapper;
import com.example.demo.model.converter.SysConfigConverter;
import com.example.demo.model.core.PageVo;
import com.example.demo.model.entity.SysConfig;
import com.example.demo.model.form.ConfigForm;
import com.example.demo.model.query.ConfigQuery;
import com.example.demo.model.vo.ConfigVO;
import com.example.demo.service.SysConfigService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private SysConfigConverter sysConfigConverter;


    @Override
    public void add(ConfigForm form) {
        Assert.isTrue(sysConfigMapper.selectCountByQuery(QueryWrapper.create().eq("configname", form.getConfigname())) == 0, "配置名称已存在");
        SysConfig entity = sysConfigConverter.toEntity(form);
        sysConfigMapper.insert(entity);
    }

    @Override
    public void update(ConfigForm form) {
        Assert.isTrue(sysConfigMapper.selectCountByQuery(QueryWrapper.create().eq("configname", form.getConfigname()).ne("id", form.getId())) == 0, "配置名称已存在");
        SysConfig entity = sysConfigConverter.toEntity(form);
        sysConfigMapper.update(entity);
    }

    @Override
    public void delete(List<String> ids) {
        sysConfigMapper.deleteBatchByIds(ids);
    }

    @Override
    public PageVo<ConfigVO> page(ConfigQuery query) {

        QueryWrapper wrapper = QueryWrapper.create();
        if (StrUtil.isNotBlank(query.getConfigname())) {
            wrapper.like("configname", query.getConfigname());
        }
        Page<SysConfig> page = sysConfigMapper.paginate(query.getPageNum(), query.getPageSize(), wrapper);
        PageVo<SysConfig> pageVo = new PageVo<>();
        pageVo.setList(page.getRecords());
        pageVo.setTotal(page.getTotalRow());
        return sysConfigConverter.toPageVo(pageVo);
    }

    @Override
    public ConfigForm form(String id) {
        SysConfig sysConfig = sysConfigMapper.selectOneById(id);
        Assert.notNull(sysConfig,"系统配置不存在");
        return sysConfigConverter.toForm(sysConfig);
    }

    @Override
    public String getConfigValueByKey(String configKey) {
        QueryWrapper wrapper = QueryWrapper.create().eq("configkey", configKey);
        SysConfig sysConfig = sysConfigMapper.selectOneByQuery(wrapper);
        return sysConfig != null ? sysConfig.getConfigvalue() : "";
    }

}




